import { Response, ENUM_ERROR } from "qqlx-core";

import { getErrorTrans } from "@lib/trans.com.error";
import { isObject } from "@lib/com.verify";

export function checkResponse<T>(qqlxRes: Response<T>) {
  if (qqlxRes.code !== ENUM_ERROR.SUCCESS) {
    throw qqlxRes;
  }

  return qqlxRes.data;
}

export function getDefaultResponse<T>(): Response<T> {
  return {
    code: ENUM_ERROR.NONE,
    data: null as T,
    message: "",
  };
}

export function parseErrorMessage(mess: any, options?: { isQuick: boolean }) {
  const response = getDefaultResponse<null>();
  if (!isObject(mess)) {
    return { ...response, message: String(mess) || "未知错误" };
  }

  // 传输错误信息
  const error = mess as Response<null> & Error;
  response.code = error.code || -1;
  response.message = error.message || "未知错误";
  if (options?.isQuick) return response;

  // 翻译错误码
  const trans = getErrorTrans(response.code);
  if (trans) {
    const msg = response.message;
    response.message = `${trans.zh}（${msg}）`;
  }
  return response;
}
